// 声音管理组合式函数
import { ref } from 'vue'

export function useSoundManager() {
  // 音频对象缓存
  const audioCache = new Map<string, HTMLAudioElement>()

  // 定时器引用
  const openTimers = ref<NodeJS.Timeout[]>([])
  const closeTimers = ref<NodeJS.Timeout[]>([])
  const closeFlashIntervals = ref<NodeJS.Timeout[]>([])
  
  // 已播放标记（防止重复播放）
  const playedOpenTimes = new Set<string>()
  const playedCloseTimes = new Set<string>()

  // 音频文件路径映射
  const soundFiles = {
    fiveTimes: '/video/fiveTimes.wav',      // 开盘前5分钟
    longOnce: '/video/longOnce.wav',        // 开盘前1分钟 & 收盘前1分钟
    placeOrder: '/video/placeOrder.wav',    // 下单成功
    cancelOrder: '/video/cancelOrder.wav',  // 撤单成功
    success: '/video/sucess.wav'            // 成交成功
  }

  // 预加载音频文件
  const preloadAudio = () => {
    Object.entries(soundFiles).forEach(([key, path]) => {
      try {
        const audio = new Audio(path)
        audio.preload = 'auto'
        // 添加错误处理，忽略缓存错误
        audio.addEventListener('error', (e) => {
          // 忽略缓存操作不支持的错误
          if (e.target && (e.target as any).error?.message?.includes('CACHE')) {
            return
          }
          console.warn(`音频加载警告 [${key}]:`, e)
        })
        audioCache.set(key, audio)
      } catch (error) {
        console.warn(`音频预加载失败 [${key}]:`, error)
      }
    })
  }

  // 播放声音
  const playSound = (soundType: keyof typeof soundFiles) => {
    try {
      const audio = audioCache.get(soundType)
      if (audio) {
        // 重置播放位置
        audio.currentTime = 0
        audio.play().catch(error => {
          console.warn(`🔇 音频播放失败 [${soundType}]:`, error.message)
        })
        console.log(`🔊 播放音频: ${soundType}`)
      } else {
        console.warn(`⚠️ 音频未找到 [${soundType}]，可能未预加载`)
        // 尝试直接创建并播放
        const path = soundFiles[soundType]
        if (path) {
          const newAudio = new Audio(path)
          newAudio.play().catch(error => {
            console.error(`❌ 音频播放失败 [${soundType}]:`, error)
          })
        }
      }
    } catch (error) {
      console.error(`❌ 播放音频异常 [${soundType}]:`, error)
    }
  }

  // 获取当前时间的小时和分钟
  const getCurrentTime = () => {
    const now = new Date()
    return {
      hours: now.getHours(),
      minutes: now.getMinutes(),
      seconds: now.getSeconds()
    }
  }

  // 计算到指定时间的毫秒数
  const getTimeUntil = (targetHours: number, targetMinutes: number, targetSeconds: number = 0) => {
    const now = new Date()
    const target = new Date()
    target.setHours(targetHours, targetMinutes, targetSeconds, 0)

    // 如果目标时间已过，设置为明天
    if (target <= now) {
      target.setDate(target.getDate() + 1)
    }

    return target.getTime() - now.getTime()
  }

  // 设置开盘提醒
  // 开盘时间：8:55, 8:59, 10:30, 13:30, 20:59, 21:00
  const setupMarketOpenReminders = () => {
    // 清除现有定时器
    openTimers.value.forEach(timer => clearTimeout(timer))
    openTimers.value = []
    
    // 开盘时间点配置
    const openTimes = [
      { hour: 8, minute: 55 },
      { hour: 8, minute: 59 },
      { hour: 10, minute: 30 },
      { hour: 13, minute: 30 },
      { hour: 20, minute: 59 },
      { hour: 21, minute: 0 },
      // { hour: 17, minute: 25 } // 测试
    ]
    
    // 为每个开盘时间设置定时器
    openTimes.forEach(({ hour, minute }) => {
      const timeKey = `${hour}:${minute}`
      const timeUntil = getTimeUntil(hour, minute)
      
      const timer = setTimeout(() => {
        // 检查是否已播放过（防止重复）
        if (!playedOpenTimes.has(timeKey)) {
          console.log(`🔔 开盘提醒: ${hour}:${minute}`)
          playSound('fiveTimes')
          playedOpenTimes.add(timeKey)
          
          // 第二天清除标记
          setTimeout(() => {
            playedOpenTimes.delete(timeKey)
          }, 24 * 60 * 60 * 1000)
        }
      }, timeUntil)
      
      openTimers.value.push(timer)
    })
  }

  // 设置收盘提醒
  // 收盘时间：10:15, 11:30, 15:00, 23:00, 1:00, 2:30
  // 收盘前1分钟开始闪烁，最后1秒播放longOnce提示音
  const setupMarketCloseReminders = () => {
    // 清除现有定时器
    closeTimers.value.forEach(timer => clearTimeout(timer))
    closeTimers.value = []
    closeFlashIntervals.value.forEach(interval => clearInterval(interval))
    closeFlashIntervals.value = []
    
    // 收盘时间点配置
    const closeTimes = [
      { hour: 10, minute: 15 },
      { hour: 11, minute: 30 },
      { hour: 15, minute: 0 },
      { hour: 23, minute: 0 },
      { hour: 1, minute: 0 },   // 凌晨1:00
      { hour: 2, minute: 30 },   // 凌晨2:30
      // { hour: 17, minute: 21 } // 测试
    ]
    
    // 为每个收盘时间设置提醒
    closeTimes.forEach(({ hour, minute }) => {
      const timeKey = `${hour}:${minute}`
      
      // 收盘前1分钟开始闪烁（这里只设置定时器，实际闪烁由外部组件处理）
      const timeUntilFlash = getTimeUntil(hour, minute - 1)
      const flashTimer = setTimeout(() => {
        console.log(`⚠️ 收盘前1分钟闪烁提醒: ${hour}:${minute}`)
        // 触发闪烁事件（由外部监听）
        window.dispatchEvent(new CustomEvent('market-close-flash', {
          detail: { hour, minute }
        }))
      }, timeUntilFlash)
      closeTimers.value.push(flashTimer)
      
      // 收盘最后1秒播放提示音
      const timeUntilSound = getTimeUntil(hour, minute, 0) - 1000 // 提前1秒
      const soundTimer = setTimeout(() => {
        // 检查是否已播放过（防止重复）
        if (!playedCloseTimes.has(timeKey)) {
          console.log(`🔔 收盘提醒: ${hour}:${minute}`)
          playSound('longOnce')
          playedCloseTimes.add(timeKey)
          
          // 停止闪烁
          window.dispatchEvent(new CustomEvent('market-close-stop-flash', {
            detail: { hour, minute }
          }))
          
          // 第二天清除标记
          setTimeout(() => {
            playedCloseTimes.delete(timeKey)
          }, 24 * 60 * 60 * 1000)
        }
      }, timeUntilSound)
      closeTimers.value.push(soundTimer)
    })
  }

  // 初始化声音管理器
  const initSoundManager = () => {
    preloadAudio()
    setupMarketOpenReminders()
    setupMarketCloseReminders()

    // 每天重新设置提醒（在午夜后重新设置）
    const timeUntilMidnight = getTimeUntil(0, 0, 1) // 午夜后1秒
    setTimeout(() => {
      setupMarketOpenReminders()
      setupMarketCloseReminders()

      // 设置每日重复
      setInterval(() => {
        setupMarketOpenReminders()
        setupMarketCloseReminders()
      }, 24 * 60 * 60 * 1000) // 每24小时
    }, timeUntilMidnight)
  }

  // 交易相关声音
  const playPlaceOrderSound = () => playSound('placeOrder')
  const playCancelOrderSound = () => playSound('cancelOrder')
  const playSuccessSound = () => playSound('success')

  // 测试所有声音
  const testAllSounds = () => {
    setTimeout(() => {
      playSound('fiveTimes')
    }, 0)
    setTimeout(() => {
      playSound('longOnce')
    }, 1000)
    setTimeout(() => {
      playSound('placeOrder')
    }, 2000)
    setTimeout(() => {
      playSound('cancelOrder')
    }, 3000)
    setTimeout(() => {
      playSound('success')
    }, 4000)
  }

  // 测试开盘提醒（立即触发）
  const testMarketOpenReminders = () => {
    setTimeout(() => {
      playSound('fiveTimes')
    }, 0)
    setTimeout(() => {
      playSound('longOnce')
    }, 2000)
  }

  // 测试收盘提醒（立即触发）
  const testMarketCloseReminders = () => {
    let count = 0
    const interval = setInterval(() => {
      playSound('longOnce')
      count++
      if (count >= 3) {
        clearInterval(interval)
      }
    }, 1000)
  }

  // 清理定时器
  const cleanup = () => {
    openTimers.value.forEach(timer => clearTimeout(timer))
    openTimers.value = []
    closeTimers.value.forEach(timer => clearTimeout(timer))
    closeTimers.value = []
    closeFlashIntervals.value.forEach(interval => clearInterval(interval))
    closeFlashIntervals.value = []
    playedOpenTimes.clear()
    playedCloseTimes.clear()
  }

  // 播放登录成功提示音
  const playLoginSuccessSound = () => {
    console.log('🔔 登录成功提示音')
    playSound('fiveTimes')
  }

  return {
    playSound,
    playPlaceOrderSound,
    playCancelOrderSound,
    playSuccessSound,
    playLoginSuccessSound,
    testAllSounds,
    testMarketOpenReminders,
    testMarketCloseReminders,
    initSoundManager,
    cleanup
  }
}
